import { Request, Response, NextFunction } from 'express';
import { getCachedPrisma, prisma } from '../../config/database';
import { CACHE_PREFIXES, deleteCacheByPattern } from '../../config/redis';
import { logger } from '../../utils/logger';
import { BaseController } from '../../utils/autoBind';
import { ResponseUtils } from '../../utils/responseUtils';
import { BUSINESS_ERROR_CODES, VALIDATION_ERROR_CODES } from '../../utils/errorCodes';
import { getFileUrl, deleteFile } from '../../middleware/upload';

/**
 * 艺人作品管理控制器
 * 提供艺人作品的增删改查功能
 */
export class WorkController extends BaseController {
  // 获取作品列表
  async getWorks(req: Request, res: Response, next: NextFunction): Promise<void> {
    try {
      const { page = 1, limit = 20, artistId, search, isRepresentative } = req.query;
      const pageNum = parseInt(page as string);
      const limitNum = parseInt(limit as string);
      const skip = (pageNum - 1) * limitNum;

      // 构建查询条件
      const where: any = {};
      
      if (artistId) {
        where.artistId = parseInt(artistId as string);
      }
      
      if (isRepresentative !== undefined) {
        where.isRepresentative = isRepresentative === 'true';
      }
      
      if (search) {
        where.OR = [
          { title: { contains: search as string } },
          { description: { contains: search as string } }
        ];
      }

      // 查询作品列表
      const [works, total] = await Promise.all([
        prisma.artistWork.findMany({
          where,
          skip,
          take: limitNum,
          orderBy: { createdAt: 'desc' },
          include: {
            artist: {
              select: {
                id: true,
                name: true,
                avatar: true
              }
            }
          }
        }),
        prisma.artistWork.count({ where })
      ]);

      // 格式化响应数据
      const formattedWorks = works.map((work: any) => ({
        id: work.id,
        title: work.title,
        duration: work.duration,
        description: work.description,
        releaseDate: work.releaseDate,
        isRepresentative: work.isRepresentative,
        audioUrl: work.audioUrl,
        createdAt: work.createdAt,
        artist: work.artist
      }));

      ResponseUtils.paginated(res, formattedWorks, total, pageNum, limitNum, '获取作品列表成功');
    } catch (error) {
      next(error);
    }
  }

  // 获取作品详情
  async getWork(req: Request, res: Response, next: NextFunction): Promise<void> {
    try {
      const { id } = req.params;
      const workId = parseInt(id);

      if (isNaN(workId)) {
        ResponseUtils.sendError(res, VALIDATION_ERROR_CODES.FIELD_TYPE_ERROR, '无效的作品ID');
        return;
      }

      // 获取缓存 Prisma 客户端
      const cachedPrisma = await getCachedPrisma();

      const work = await cachedPrisma.artistWork.findUnique({
        where: { id: workId },
        include: {
          artist: {
            select: {
              id: true,
              name: true,
              avatar: true,
              genre: true,
              country: true
            }
          }
        }
      });

      if (!work) {
        ResponseUtils.sendError(res, BUSINESS_ERROR_CODES.RESOURCE_NOT_FOUND, '作品不存在');
        return;
      }

      ResponseUtils.success(res, work, '获取作品详情成功');
    } catch (error) {
      next(error);
    }
  }

  // 创建作品
  async createWork(req: Request, res: Response, next: NextFunction): Promise<void> {
    try {
      const { artistId, title, duration, description, releaseDate, isRepresentative, audioUrl } = req.body;

      // 验证必填字段
      if (!artistId || !title) {
        ResponseUtils.sendError(res, VALIDATION_ERROR_CODES.REQUIRED_FIELD_MISSING, '艺人和作品标题不能为空');
        return;
      }

      // 验证艺人是否存在
      const artist = await prisma.artist.findUnique({
        where: { id: parseInt(artistId) }
      });

      if (!artist) {
        ResponseUtils.sendError(res, BUSINESS_ERROR_CODES.RESOURCE_NOT_FOUND, '艺人不存在');
        return;
      }

      // 创建作品
      const work = await prisma.artistWork.create({
        data: {
          artistId: parseInt(artistId),
          title,
          duration,
          description,
          releaseDate: releaseDate ? new Date(releaseDate) : null,
          isRepresentative: isRepresentative || false,
          audioUrl
        },
        include: {
          artist: {
            select: {
              id: true,
              name: true,
              avatar: true
            }
          }
        }
      });

      // 清除相关缓存
      await deleteCacheByPattern(`${CACHE_PREFIXES.ARTIST}:${artistId}:*`);

      logger.info(`管理员创建作品: ${work.id}`, { workId: work.id, artistId, adminId: (req as any).user?.id });

      ResponseUtils.success(res, work, '创建作品成功');
    } catch (error) {
      next(error);
    }
  }

  // 更新作品
  async updateWork(req: Request, res: Response, next: NextFunction): Promise<void> {
    try {
      const { id } = req.params;
      const workId = parseInt(id);
      const { title, duration, description, releaseDate, isRepresentative, audioUrl } = req.body;

      if (isNaN(workId)) {
        ResponseUtils.sendError(res, VALIDATION_ERROR_CODES.FIELD_TYPE_ERROR, '无效的作品ID');
        return;
      }

      // 检查作品是否存在
      const existingWork = await prisma.artistWork.findUnique({
        where: { id: workId },
        include: { artist: true }
      });

      if (!existingWork) {
        ResponseUtils.sendError(res, BUSINESS_ERROR_CODES.RESOURCE_NOT_FOUND, '作品不存在');
        return;
      }

      // 更新作品
      const updatedWork = await prisma.artistWork.update({
        where: { id: workId },
        data: {
          title,
          duration,
          description,
          releaseDate: releaseDate ? new Date(releaseDate) : null,
          isRepresentative,
          audioUrl
        },
        include: {
          artist: {
            select: {
              id: true,
              name: true,
              avatar: true
            }
          }
        }
      });

      // 清除相关缓存
      // await deleteCacheByPattern(`${CACHE_PREFIXES.ARTIST_WORK}:*`);
      await deleteCacheByPattern(`${CACHE_PREFIXES.ARTIST}:${existingWork.artistId}:*`);

      logger.info(`管理员更新作品: ${workId}`, { workId, adminId: (req as any).user?.id });

      ResponseUtils.success(res, updatedWork, '更新作品成功');
    } catch (error) {
      next(error);
    }
  }

  // 删除作品
  async deleteWork(req: Request, res: Response, next: NextFunction): Promise<void> {
    try {
      const { id } = req.params;
      const workId = parseInt(id);

      if (isNaN(workId)) {
        ResponseUtils.sendError(res, VALIDATION_ERROR_CODES.FIELD_TYPE_ERROR, '无效的作品ID');
        return;
      }

      // 检查作品是否存在
      const existingWork = await prisma.artistWork.findUnique({
        where: { id: workId },
        include: { artist: true }
      });

      if (!existingWork) {
        ResponseUtils.sendError(res, BUSINESS_ERROR_CODES.RESOURCE_NOT_FOUND, '作品不存在');
        return;
      }

      // 删除音频文件
      if (existingWork.audioUrl) {
        const filename = existingWork.audioUrl.split('/').pop();
        if (filename) {
          deleteFile(filename, 'audio');
        }
      }
      // 删除作品
      await prisma.artistWork.delete({
        where: { id: workId }
      });

      // 清除相关缓存
      // await deleteCacheByPattern(`${CACHE_PREFIXES.ARTIST_WORK}:*`);
      await deleteCacheByPattern(`${CACHE_PREFIXES.ARTIST}:${existingWork.artistId}:*`);

      logger.info(`管理员删除作品: ${workId}`, { workId, adminId: (req as any).user?.id });

      ResponseUtils.success(res, null, '删除作品成功');
    } catch (error) {
      next(error);
    }
  }

  // 批量删除作品
  async batchDeleteWorks(req: Request, res: Response, next: NextFunction): Promise<void> {
    try {
      const { ids } = req.body;

      if (!Array.isArray(ids) || ids.length === 0) {
        ResponseUtils.sendError(res, VALIDATION_ERROR_CODES.REQUIRED_FIELD_MISSING, '请选择要删除的作品');
        return;
      }

      // 验证所有ID都是有效的
      const workIds = ids.map(id => parseInt(id)).filter(id => !isNaN(id));
      
      if (workIds.length !== ids.length) {
        ResponseUtils.sendError(res, VALIDATION_ERROR_CODES.FIELD_TYPE_ERROR, '包含无效的作品ID');
        return;
      }

      // 检查作品是否存在
      const existingWorks = await prisma.artistWork.findMany({
        where: { id: { in: workIds } },
        include: { artist: true }
      });

      if (existingWorks.length !== workIds.length) {
        ResponseUtils.sendError(res, BUSINESS_ERROR_CODES.RESOURCE_NOT_FOUND, '部分作品不存在');
        return;
      }

      // 批量删除作品
      await prisma.artistWork.deleteMany({
        where: { id: { in: workIds } }
      });

      // 清除相关缓存
      // await deleteCacheByPattern(`${CACHE_PREFIXES.ARTIST_WORK}:*`);
      const artistIds = [...new Set(existingWorks.map(work => work.artistId))];
      for (const artistId of artistIds) {
        await deleteCacheByPattern(`${CACHE_PREFIXES.ARTIST}:${artistId}:*`);
      }

      logger.info(`管理员批量删除作品: ${workIds.join(', ')}`, { workIds, adminId: (req as any).user?.id });

      ResponseUtils.success(res, { deletedCount: workIds.length }, '批量删除作品成功');
    } catch (error) {
      next(error);
    }
  }

  // 获取作品统计信息
  async getWorkStatistics(_req: Request, res: Response, next: NextFunction): Promise<void> {
    try {
      // 获取缓存 Prisma 客户端
      const cachedPrisma = await getCachedPrisma();

      // 并行查询统计数据
      const [
        totalWorks,
        representativeWorks,
        worksByArtist,
        recentWorks
      ] = await Promise.all([
        // 总作品数
        cachedPrisma.artistWork.count(),
        
        // 代表作数量
        cachedPrisma.artistWork.count({
          where: { isRepresentative: true }
        }),
        
        // 按艺人分组的作品数量
        cachedPrisma.artistWork.groupBy({
          by: ['artistId'],
          _count: { id: true },
          orderBy: { _count: { id: 'desc' } },
          take: 10
        }),
        
        // 最近创建的作品
        cachedPrisma.artistWork.findMany({
          take: 5,
          orderBy: { createdAt: 'desc' },
          include: {
            artist: {
              select: {
                id: true,
                name: true,
                avatar: true
              }
            }
          }
        })
      ]);

      // 获取艺人信息
      const artistIds = worksByArtist.map((item: any) => item.artistId);
      const artists = await cachedPrisma.artist.findMany({
        where: { id: { in: artistIds } },
        select: { id: true, name: true, avatar: true }
      });

      // 格式化按艺人分组的统计数据
      const worksByArtistFormatted = worksByArtist.map((item: any) => {
        const artist = artists.find((a: any) => a.id === item.artistId);
        return {
          artistId: item.artistId,
          artistName: artist?.name || '未知艺人',
          artistAvatar: artist?.avatar,
          workCount: item._count.id
        };
      });

      const statistics = {
        totalWorks,
        representativeWorks,
        worksByArtist: worksByArtistFormatted,
        recentWorks
      };

      ResponseUtils.success(res, statistics, '获取作品统计信息成功');
    } catch (error) {
      next(error);
    }
  }

  // 获取艺人的作品列表
  async getArtistWorks(req: Request, res: Response, next: NextFunction): Promise<void> {
    try {
      const { artistId } = req.params;
      const { page = 1, limit = 20 } = req.query;
      const pageNum = parseInt(page as string);
      const limitNum = parseInt(limit as string);
      const skip = (pageNum - 1) * limitNum;

      const artistIdNum = parseInt(artistId);
      if (isNaN(artistIdNum)) {
        ResponseUtils.sendError(res, VALIDATION_ERROR_CODES.FIELD_TYPE_ERROR, '无效的艺人ID');
        return;
      }

      // 检查艺人是否存在
      const artist = await prisma.artist.findUnique({
        where: { id: artistIdNum }
      });

      if (!artist) {
        ResponseUtils.sendError(res, BUSINESS_ERROR_CODES.RESOURCE_NOT_FOUND, '艺人不存在');
        return;
      }

      // 查询艺人的作品
      const [works, total] = await Promise.all([
        prisma.artistWork.findMany({
          where: { artistId: artistIdNum },
          skip,
          take: limitNum,
          orderBy: { createdAt: 'desc' },
          select: {
            id: true,
            title: true,
            duration: true,
            description: true,
            releaseDate: true,
            isRepresentative: true,
            audioUrl: true,
            createdAt: true
          }
        }),
        prisma.artistWork.count({
          where: { artistId: artistIdNum }
        })
      ]);

      ResponseUtils.paginated(res, works, total, pageNum, limitNum, '获取艺人作品列表成功');
    } catch (error) {
      next(error);
    }
  }

  // 上传作品音频
  async uploadWorkAudio(req: Request, res: Response, next: NextFunction): Promise<void> {
    try {
      const { id } = req.params;
      const workId = parseInt(id);

      if (isNaN(workId)) {
        ResponseUtils.sendError(res, VALIDATION_ERROR_CODES.FIELD_TYPE_ERROR, '无效的作品ID');
        return;
      }

      // 检查作品是否存在
      const existingWork = await prisma.artistWork.findUnique({
        where: { id: workId },
        include: { artist: true }
      });

      if (!existingWork) {
        ResponseUtils.sendError(res, BUSINESS_ERROR_CODES.RESOURCE_NOT_FOUND, '作品不存在');
        return;
      }

      // 检查是否有上传的文件
      if (!req.file) {
        ResponseUtils.sendError(res, VALIDATION_ERROR_CODES.REQUIRED_FIELD_MISSING, '请选择要上传的音频文件');
        return;
      }

      // 如果已有音频文件，先删除旧文件
      if (existingWork.audioUrl) {
        const oldFilename = existingWork.audioUrl.split('/').pop();
        if (oldFilename) {
          deleteFile(oldFilename, 'audio');
        }
      }

      // 生成新的音频URL
      const audioUrl = getFileUrl(req.file.filename, 'audio');

      // 更新作品的音频URL
      const updatedWork = await prisma.artistWork.update({
        where: { id: workId },
        data: { audioUrl },
        include: {
          artist: {
            select: {
              id: true,
              name: true,
              avatar: true
            }
          }
        }
      });

      // 清除相关缓存
      await deleteCacheByPattern(`${CACHE_PREFIXES.ARTIST}:${existingWork.artistId}:*`);

      logger.info(`管理员上传作品音频: ${workId}`, { 
        workId, 
        audioUrl, 
        adminId: (req as any).user?.id 
      });

      ResponseUtils.success(res, updatedWork, '上传作品音频成功');
    } catch (error) {
      next(error);
    }
  }

  // 删除作品音频
  async deleteWorkAudio(req: Request, res: Response, next: NextFunction): Promise<void> {
    try {
      const { id } = req.params;
      const workId = parseInt(id);

      if (isNaN(workId)) {
        ResponseUtils.sendError(res, VALIDATION_ERROR_CODES.FIELD_TYPE_ERROR, '无效的作品ID');
        return;
      }

      // 检查作品是否存在
      const existingWork = await prisma.artistWork.findUnique({
        where: { id: workId },
        include: { artist: true }
      });

      if (!existingWork) {
        ResponseUtils.sendError(res, BUSINESS_ERROR_CODES.RESOURCE_NOT_FOUND, '作品不存在');
        return;
      }

      // 检查是否有音频文件
      if (!existingWork.audioUrl) {
        ResponseUtils.sendError(res, BUSINESS_ERROR_CODES.RESOURCE_NOT_FOUND, '作品没有音频文件');
        return;
      }

      // 删除音频文件
      const filename = existingWork.audioUrl.split('/').pop();
      if (filename) {
        deleteFile(filename, 'audio');
      }

      // 更新作品，清除音频URL
      const updatedWork = await prisma.artistWork.update({
        where: { id: workId },
        data: { audioUrl: null },
        include: {
          artist: {
            select: {
              id: true,
              name: true,
              avatar: true
            }
          }
        }
      });

      // 清除相关缓存
      await deleteCacheByPattern(`${CACHE_PREFIXES.ARTIST}:${existingWork.artistId}:*`);

      logger.info(`管理员删除作品音频: ${workId}`, { 
        workId, 
        adminId: (req as any).user?.id 
      });

      ResponseUtils.success(res, updatedWork, '删除作品音频成功');
    } catch (error) {
      next(error);
    }
  }
}
